from core.freeze_support import init_process
from ui.main_window import MainWindow
from PyQt5.QtWidgets import QApplication, QMessageBox
# import winerror
# import win32api
# import win32event
import sys
import os
# 首先导入并调用multiprocessing.freeze_support()
import multiprocessing
multiprocessing.freeze_support()


def main():
    # 初始化多进程支持
    init_process()

    # # 创建互斥锁
    # mutex_name = "Global\\MessageAlertSystem_SingleInstance"
    # mutex = win32event.CreateMutex(None, 1, mutex_name)
    # last_error = win32api.GetLastError()

    # if last_error == winerror.ERROR_ALREADY_EXISTS:
    #     # 如果互斥锁已存在，说明程序已经在运行
    #     QMessageBox.warning(None, "警告", "程序已经在运行中！")
    #     win32api.CloseHandle(mutex)  # 清理互斥锁句柄
    #     return

    app = QApplication(sys.argv)

    try:
        window = MainWindow()
        window.show()
        exit_code = app.exec_()
    finally:
        # 确保在程序退出时释放互斥锁
        # win32api.CloseHandle(mutex)
        # 清理其他资源
        print("程序退出")

    sys.exit(exit_code)


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        # 在发生异常时显示错误信息
        if not QApplication.instance():
            app = QApplication(sys.argv)
        QMessageBox.critical(None, "错误", f"程序发生错误：{str(e)}")
        sys.exit(1)
